define(function (require) {
    require('../../../c/base/index');

    require('../../../c/nav/index');
    require('./outflat-list-tpl');
    var outflatListTpl = juicer.templates['outflat-list.juicer.html'];

    var flatIndex=10;
    var firstTime = true;
    var elTbody = $('#J_Tbody');
    var timer;
    var pageSize = 10;//每页显示的数据
    // var pageTotal = 0;
    var pageData = 1;//页数
    var visual = 5;//分页器可显示的页数
    var pageIndex;//总页数
    var pageBase = 1;
    var count = 0;
    $(".fa-circle-o").each(function () {
        if ($(this).parents("a").text() == "外店管理") {
            $(this).parents("a").parents("li").addClass("active");
        }
    });
    var page = {
        init: function(){
            this.initChangeList();
            this.initValidator();
            this.initBind();
            this.getCountryName();
        },
        //分页
        initpagination:function(pageTotal){
            var self = this;
            if(pageTotal%pageSize != 0){
                pageIndex = parseInt(pageTotal /pageSize) + 1;
            }else{
                pageIndex = parseInt(pageTotal /pageSize);
            }

            if (pageIndex != 0 && pageTotal != 0) {
                $('#pagination li').remove();
                self.initfourBtn();
                self.appendSign(pageBase,pageIndex);
                self.pageMessage(pageData, pageSize, pageTotal);
            }else{
                $('#pagination').attr('display','none');
            }
        },
        initfourBtn:function(){
            var obj = $('<li id=first><a href=#>首页</a></li>');
            $('#pagination').append(obj);
            var obj = $('<li id=prev><a href=#>上页</a></li>');
            $('#pagination').append(obj);
            var obj = $('<li id=next><a href=#>下页</a></li>');
            $('#pagination').append(obj);
            var obj = $('<li id=last><a href=#>末页</a></li>');
            $('#pagination').append(obj);
        },
        appendSign: function(pageBase,pageIndex){
            // $('#pagination').children().remove();
            if((pageIndex - pageBase + 1) <= visual){
                for(var i = pageBase; i <= pageIndex; i++){
                    var obj = $("<li id=" + i + "><a>" + i +"</a></li>");
                    obj.insertBefore($('#pagination li').eq(-2));
                }
            }else{
                for(var i = pageBase; i <= (visual+pageBase-1); i++){
                    var obj = $("<li id=" + i + "><a>" + i +"</a></li>");
                    obj.insertBefore($('#pagination li').eq(-2));
                }
                var more = $("<li id=more><a>...</a></li>");
                more.insertBefore($('#pagination li').eq(-2));
            }
        },
        pageMessage:function(pageData, pageSize, pageTotal){
            $('#begin').text(1 + (pageData - 1) * pageSize);
            if(pageData * pageSize > pageTotal){
                $('#to').text(pageTotal);
            }else{
                $('#to').text(pageData * pageSize);
            }
            $('#total').text(pageTotal);
        },
        bindEvent:function(pageTotal){
            var self = this;
            $('#pagination li').on('click',function(){
                var pointed = $(this).attr('id');
                if(pointed == "first"){
                    pageBase = 1;
                    pageData = 1;
                    $('#pagination li').remove();
                    self.initfourBtn();
                    self.appendSign(pageBase,pageIndex);
                    self.bindEvent(pageTotal);
                    self.pageMessage(pageData, pageSize, pageTotal);
                    var add = "#" + pageData;
                    $(add).parent().find("li").removeClass('active');
                    $(add).addClass('active');

                }else if(pointed == "prev"){
                    if(pageData == 1){
                        pageData = 1;
                        var add = "#" + pageData;
                        $(add).parent().find("li").removeClass('active');
                        $(add).addClass('active');
                        self.pageMessage(pageData, pageSize, pageTotal);
                    }else{
                        if(pageData == pageBase){
                            pageData -= 1;
                            pageBase -= visual;
                            $('#pagination li').remove();
                            self.initfourBtn();
                            self.appendSign(pageBase,pageIndex);
                            self.bindEvent(pageTotal);
                            self.pageMessage(pageData, pageSize, pageTotal);
                            var add = "#" + pageData;
                            $(add).parent().find("li").removeClass('active');
                            $(add).addClass('active');
                        }else{
                            pageData -= 1;
                            var add = "#" + pageData;
                            self.pageMessage(pageData, pageSize, pageTotal);
                            $(add).parent().find("li").removeClass('active');
                            $(add).addClass('active');
                        }

                    }
                }else if(pointed == "next"){
                    if(pageData != pageIndex){
                        if(pageData == pageBase + visual - 1){
                            pageBase += visual;
                            pageData += 1;
                            $('#pagination li').remove();
                            self.initfourBtn();
                            self.appendSign(pageBase,pageIndex);
                            self.bindEvent(pageTotal);
                            self.pageMessage(pageData, pageSize, pageTotal);
                            var add = "#" + pageData;
                            $(add).parent().find("li").removeClass('active');
                            $(add).addClass('active');
                        }else{
                            pageData += 1;
                            var add = "#" + pageData;
                            self.pageMessage(pageData, pageSize, pageTotal);
                            $(add).parent().find("li").removeClass('active');
                            $(add).addClass('active');
                        }
                    }
                }else if(pointed == "last"){
                    var moreItem = Math.ceil(pageTotal/pageSize)%visual;
                    if (moreItem!=0) {
                        pageBase = pageIndex - moreItem + 1;
                        pageData = pageIndex;
                        $('#pagination li').remove();
                        self.initfourBtn();
                        self.appendSign(pageBase,pageIndex);
                        self.bindEvent(pageTotal);
                        self.pageMessage(pageData, pageSize, pageTotal);
                        var add = "#" + pageData;
                        $(add).parent().find("li").removeClass('active');
                        $(add).addClass('active');
                    }else{
                        pageBase = pageIndex - visual + 1;
                        pageData = pageIndex;
                        $('#pagination li').remove();
                        self.initfourBtn();
                        self.appendSign(pageBase,pageIndex);
                        self.bindEvent(pageTotal);
                        self.pageMessage(pageData, pageSize, pageTotal);
                        var add = "#" + pageData;
                        $(add).parent().find("li").removeClass('active');
                        $(add).addClass('active');
                    }
                }else if(pointed == "more"){
                    pageBase += visual;
                    pageData = pageBase;
                    $('#pagination li').remove();
                    self.initfourBtn();
                    self.appendSign(pageBase,pageIndex);
                    self.bindEvent(pageTotal);
                    self.pageMessage(pageData, pageSize, pageTotal);
                    self.jump(pageTotal);

                }else{
                    pageData = parseInt($(this).attr('id'));
                    var add = "#" + pageData;
                    self.pageMessage(pageData, pageSize, pageTotal);
                    $(add).parent().find("li").removeClass('active');
                    $(add).addClass('active');
                }
                dataString = JSON.stringify({
                    isp: flatIndex,
                    cityName: $('#query_country option:selected').text(),
                    innerShopId: $('#query_inId').val(),
                    outerShopId: $('#query_outId').val(),
                    innerShopName: $('#query_shopName').val(),
                    pageSize: pageSize,
                    startPage: pageData
                });
                $.ajax({
                    type: 'POST',
                    // "url": 'http://dev.manage.51xianqu.com:8080/www/outflat/test.json',
                    url: CRM.getOuterUrl("/outway/shopRead/queryList"),
                    dataType: "json",
                    contentType: "application/json",
                    xhrFields: {
                        withCredentials: true
                    },
                    data: dataString,
                    success:function(data){
                        if(data.success){
                            page.showToast('数据加载中...',true,1000);
                            var waitTimer;
                            var list = data.entry;
                            if(list.totalCount == 0){
                                $("#msg_dialog_content").text('没有匹配的记录');
                                $('#msg_dialog').modal('show');
                            }else{
                                page.renderHtml(list.data);
                                window.clearTimeout(waitTimer);
                                window.setTimeout(function(){
                                    $("button[id^='dropdownMenu']").attr('disabled',false);
                                },1000);
                            }
                        }
                    },
                    error: function(e) {
                        //请求出错处理
                        $("#msg_dialog_content").text("请求服务异常！");
                        $('#msg_dialog').modal('show');
                    }
                });
            });
        },
        jump: function(pageTotal){
            var self = this;
            var add = "#" + pageData;
            $(add).parent().find("li").removeClass('active');
            $(add).addClass('active');
            self.pageMessage(pageData, pageSize, pageTotal);
            dataString = JSON.stringify({
                isp: flatIndex,
                cityName: $('#query_country option:selected').text(),
                innerShopId: $('#query_inId').val(),
                innerShopName: $('#query_shopName').val(),
                pageSize: pageSize,
                startPage: pageData
            });
            $.ajax({
                type: 'POST',
                // "url": 'http://dev.manage.51xianqu.com:8080/www/outflat/test.json',
            	url: CRM.getOuterUrl('/outway/shopRead/queryList'),
            	dataType: 'json',
            	data: dataString,
            	success: function(data){
            		if(data.success){
                         var list = data.entry;
                        page.renderHtml(list.data);
                    }else {
                        $("#msg_dialog_content").text(list.msg);
                        $('#msg_dialog').modal('show');
                    }
            	},
            	error:function(e){
                //请求出错处理
                      $("#msg_dialog_content").text("请求服务异常！");
                      $('#msg_dialog').modal('show');
            	}
            });
        },
        //外店切换
        initChangeList:function(){
            var self = this;
            $('.btn-group-define button').click(function(){
                $('.btn-group-define button').removeClass('active');
                count = $(this).prevAll().length;
                if(count == 0){
                    flatIndex = 10;
                    $('.btn-group-define button').eq(0).addClass('active');
                    // self.getChangeAjax();
                }else if(count == 1){
                    flatIndex = 1;
                    $('.btn-group-define button').eq(1).addClass('active');
                    // self.getChangeAjax();
                }else if(count == 2){
                    flatIndex = 2;
                    $('.btn-group-define button').eq(2).addClass('active');
                    // self.getChangeAjax();
                }
            });
            // self.getChangeAjax();
            self.autoUpdata();
        },
        //请求城市名称
        getCountryName: function(){
            var self = this;
            $.ajax({
                url: CRM.getOuterUrl('/shop/city/queryAllOpenCity'),
                type: 'get',
                dataType: "json",
                contentType: "application/json",
                xhrFields: {
                    withCredentials: true
                },
                data:{},
                success: function (data) {
                    if(data.status){
                        var list = data.entry;
                        $('#query_country').children().remove();
                        var html = "";
                        for(var i = 0; i < list.length; i++) {
                        // <option value="0">杭州</option>
                            html += "<option value=" + list[i].cityCode +">" + list[i].city + "</option>";
                        }
                        $('#query_country').html(html);
                    }
                },
                error: function (e) {
                    $("#msg_dialog_content").text("请求服务异常");
                    $('#msg_dialog').modal('show');
                }
            });
        },
        //请求
        getChangeAjax:function(){
            var self = this;
            dataString = JSON.stringify({
                isp: flatIndex,
                cityName: $('#query_country option:selected').text(),
                innerShopId: $('#query_inId').val(),
                outerShopId: $('#query_outId').val(),
                innerShopName: $('#query_shopName').val(),
                pageSize: pageSize,
                startPage: pageData
            });
            $.ajax({
                url: CRM.getOuterUrl('/outway/shopRead/queryList'),
                // "url": 'http://dev.manage.51xianqu.com:8080/www/outflat/test.json',
                type: 'POST',
                dataType: "json",
                contentType: "application/json",
                data: dataString,
                xhrFields: {
                    withCredentials: true
                },
                success: function(data){
                    if(data.success){
                        page.showToast("数据加载中...",true,1000);
                        var list = data.entry;
                        // console.log(list.data.length);
                        if(list.totalCount == 0 || list['totalCount'] == null){
                            elTbody.children().remove();
                            // $("#msg_dialog_content").text("没有匹配的记录");
                            // $('#msg_dialog').modal('show');
                        }else{
                            var waitTimer;
                            var ispName = list.data[0];
                            var string = ispName.ispName + "ID";
                            $('.tableStyle tr th').eq(3).text(string);
                            page.renderHtml(list.data);
                            $("button[id^='dropdownMenu']").attr('disabled',true);
                            window.clearTimeout(waitTimer);
                            window.setTimeout(function(){
                                $("button[id^='dropdownMenu']").attr('disabled',false);
                            },1000);
                            page.initpagination(list.totalCount);
                            page.bindEvent(list.totalCount);
                            // self.jump(list.totalCount);
                            var add = "#" + pageData;
                            $(add).parent().find("li").removeClass('active');
                            $(add).addClass('active');
                        }
                    }else{
                        elTbody.children().remove();
                        if(data.responseCode == 11201){
                            $("#msg_dialog_content").text(data.message);
                            $('#msg_dialog').modal('show');
                        }else{
                            $("#msg_dialog_content").text("没有匹配记录");
                            $('#msg_dialog').modal('show');
                        }

                    }

                },
                error: function(e) {
                    //请求出错处理
                    $("#msg_dialog_content").text("请求服务异常！");
                    $('#msg_dialog').modal('show');
                }
            });
        },
        //自动更新数据
        autoUpdata:function(){
            window.clearInterval(timer);
            setInterval(function () {
                page.getChangeAjax();
            },300000);
        },
        initBind:function(){
            var self = this;
            $('#search_btn').on('click', function(){
                elTbody.children().remove();
                if(flatIndex == 10){
                    $('.tableStyle tr th').eq(3).text("淘宝ID");
                }else if(flatIndex == 1){
                    $('.tableStyle tr th').eq(3).text("饿了么ID");
                }else if(flatIndex == 2){
                    $('.tableStyle tr th').eq(3).text("美团ID");
                }
                self.doSearch();
                self.getChangeAjax();
            });
        },
        //执行查询操作
        doSearch:function(){
            $('#J_Search').data('bootstrapValidator').validate();
        },
        initValidator:function(){
            $('#J_Search').bootstrapValidator({
                message: '输入错误',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    query_inId: {
                        message: 'error',
                        validators: {
                            regexp: {
                                regexp: /^[0-9]+$/,
                                message: '请输入数字'
                            }
                        }
                    }
                }
            });
        },
        //模版渲染
        renderHtml:function (data) {
            var html = outflatListTpl({data:data});
            elTbody.html(html);
        },
        //外店下线
        shopSuspension:function (innerShopId,outerShopId,index) {
            var self = this;
            $('#confirm_dialog').modal('hide');
            $.ajax({
                type: 'POST',
                url: CRM.getOuterUrl('/outway/shopUpdate/updateShopStatus'),
                // "url": 'http://dev.manage.51xianqu.com:8080/www/outflat/test.json',
                dataType: "json",
                async: true, //请求是否异步，默认为异步，这也是ajax重要特性
                contentType: "application/json",
                xhrFields: {
                    withCredentials: true
                },
                data: JSON.stringify({
                    innerShopId: innerShopId,
                    action: 2,
                    isp: flatIndex,
                    outerShopId:outerShopId

                }),
                contentType: "application/json",
                success: function(data) {
                    var list = data.entry;
                    page.changeItem(list,index);
                },
                error: function(e) {
                    //请求出错处理
                    $("#msg_dialog_content").text("店铺下线,请求服务异常！");
                    $('#msg_dialog').modal('show');
                }
            });
        },
        // 修改一条数据
        changeItem:function(data,index){
            var changeItemId = "#tr_" + index;
            console.log(data == null);
            if(data == null){
                $(changeItemId).children().eq(4).html("");
                $(changeItemId).children().eq(5).html("");
                $(changeItemId).children().eq(6).html("");
            }else{
                $(changeItemId).children().eq(4).html(data.innerShopStatus);
                if(data.outerShopOnline == true){
                    $(changeItemId).children().eq(5).html("上线");
                }else{
                    $(changeItemId).children().eq(5).html("下线");
                }

                $(changeItemId).children().eq(6).html(data.outerShopStatus);
            }
        },
        //外店上线
        shopOnline:function (innerShopId,outerShopId,index) {
            $('#confirm_dialog').modal('hide');
            $.ajax({
                type: 'POST',
                // "url": 'http://dev.manage.51xianqu.com:8080/www/outflat/test.json',
                url: CRM.getOuterUrl('/outway/shopUpdate/updateShopStatus'),
                dataType: "json",
                async: true, //请求是否异步，默认为异步，这也是ajax重要特性
                contentType: "application/json",
                xhrFields: {
                    withCredentials: true
                },
                data: JSON.stringify({
                    innerShopId: innerShopId,
                    action: 1,
                    isp: flatIndex,
                    outerShopId:outerShopId
                }),
                contentType: "application/json",
                success: function(data) {
                    var list = data.entry;
                    page.changeItem(list,index);

                },
                error: function(e) {
                    //请求出错处理
                    $("#msg_dialog_content").text("店铺上线,请求服务异常！");
                    $('#msg_dialog').modal('show');
                }
            });
        },
        //外店冻结
        shopFrozen:function (innerShopId,outerShopId,index){
            $('#confirm_dialog').modal('hide');
            $.ajax({
                type: 'POST',
                url: CRM.getOuterUrl('/outway/shopUpdate/updateShopStatus'),
                dataType: "json",
                // "url": 'http://dev.manage.51xianqu.com:8080/www/outflat/test.json',
                async: true, //请求是否异步，默认为异步，这也是ajax重要特性
                contentType: "application/json",
                xhrFields: {
                    withCredentials: true
                },
                data: JSON.stringify({
                    innerShopId: innerShopId,
                    action: 3,
                    isp: flatIndex,
                    outerShopId:outerShopId
                }),
                contentType: "application/json",
                success: function(data) {
                    if(data.success){
                        var list = data.entry;
                        page.changeItem(list,index);
                    }else{
                        $("#msg_dialog_content").text("外店冻结失败！");
                        $('#msg_dialog').modal('show');
                    }
                },
                error: function(e) {
                    //请求出错处理
                    $("#msg_dialog_content").text("外店冻结,请求服务异常！");
                    $('#msg_dialog').modal('show');
                }
            });
        },
        //外店解冻
        shopOffFrozen:function (innerShopId,outerShopId,index){
            $('#confirm_dialog').modal('hide');
            $.ajax({
                type: 'POST',
                url: CRM.getOuterUrl('/outway/shopUpdate/updateShopStatus'),
                dataType: "json",
                // "url": 'http://dev.manage.51xianqu.com:8080/www/outflat/test.json',
                async: true, //请求是否异步，默认为异步，这也是ajax重要特性
                contentType: "application/json",
                xhrFields: {
                    withCredentials: true
                },
                data: JSON.stringify({
                    innerShopId: innerShopId,
                    action: 4,
                    isp: flatIndex,
                    outerShopId:outerShopId
                }),
                success: function(data) {
                    if(data.success){
                        var list = data.entry;
                        page.changeItem(list,index);
                    }else{
                        $("#msg_dialog_content").text("外店解冻,请求服务异常！");
                        $('#msg_dialog').modal('show');
                    }

                },
                error: function(e) {
                    //请求出错处理
                    $("#msg_dialog_content").text("外店解冻,请求服务异常！");
                    $('#msg_dialog').modal('show');
                }
            });
        },
        //打开店铺链接
        openSrc:function (id) {
            if(id != 'null'){
                window.open(id);
            }else{
                $("#msg_dialog_content").text("此平台没有店铺详情页");
                $('#msg_dialog').modal('show');
            }
        },
        //店铺详细信息
        // shopDetailed:function (id) {
        //     window.open('/crm/www/shop/shopConfig.html?id=' + id);
        // },
        //店铺详细信息
        openShopSrc:function (id) {
            window.open('/crm/www/shop/shopConfig.html?id=' + id);
        },
        //展示一个toast
        showToast: function (text, isok, timer, callback) {
            var clazz = isok ? 'hui-toast-icon-ok' : 'hui-toast-icon-false',
                xt = '<div class="hui-toast">' +
                    '<div class="hui-toast-cont">' +
                    '   <i class="hui-toast-icon ' + clazz + '"></i>' +
                    '   <p class="hui-toast-text">' + text + '</p >' +
                    '</div>' +
                    '</div>';
            $('#search_btn').attr('disabled',true);
            $(document.body).append(xt);
            setTimeout(function () {
                $('.hui-toast').fadeOut('normal', function () {
                    $('#search_btn').attr('disabled',false);
                    $('.hui-toast').hide().remove();
                    callback && callback();
                });
            }, timer);
        }
    }
    window.getChangeAjax = page.getChangeAjax;
    window.doSearch = $.proxy(page.doSearch, page);
    window.shopOnline = $.proxy(page.shopOnline, page);
    window.shopSuspension = $.proxy(page.shopSuspension, page);
    window.shopFrozen = $.proxy(page.shopFrozen, page);
    window.shopOffFrozen = $.proxy(page.shopOffFrozen, page);
    window.openSrc = $.proxy(page.openSrc, page);
    window.shopDetailed = $.proxy(page.shopDetailed, page);
    window.openShopSrc = $.proxy(page.openShopSrc, page);
    window.changeItem = $.proxy(page.changeItem, page);
    page.init();
});